package com.finalministry.db.message;

import java.text.MessageFormat;

public class MessageFormatter {

	/**
	 * print the arguments as plain text fromat. Use this method when an
	 * argument exception occur
	 * 
	 * @param arguments
	 * @return args as plain text format
	 */
	public static String printArguments(Object[] arguments) {

		StringBuffer argumentsStringBuffer = new StringBuffer();
		int argumentPos = 0;
		if (arguments != null && arguments.length > 0) {
			argumentsStringBuffer.append(" -- Args[");
			for (int i = 0; i < arguments.length; i++) {
				Object param = arguments[i];
				if (param != null) {
					argumentsStringBuffer.append("[arg[");
					argumentsStringBuffer.append(argumentPos);
					argumentsStringBuffer.append("]");
					argumentsStringBuffer.append(param.toString());
					argumentsStringBuffer.append("]");
					argumentPos++;
				}
			}
			argumentsStringBuffer.append("]");
		}
		return argumentsStringBuffer.toString();
	}

	/**
	 * Creates a Message string and dynamically set the arguments
	 * 
	 * @param messageObject
	 * @param arguments
	 * @return Message string with dynamically set the arguments
	 */
	public static String replaceArguments(Object messageObject, Object[] arguments) {

		String messageText = "";

		try {
			if (messageObject == null) {
				messageText = "Message NULL";
			} else if (messageObject instanceof String) {
				messageText = MessageFormat.format((String) messageObject, arguments);
			} else if (messageObject instanceof Message) {
				Message message = (Message) messageObject;
				messageText = MessageFormat.format(message.getMessageText(), message.getArguments());
			} else {
				messageText = messageObject.toString();
			}
		} catch (IllegalArgumentException ex) {
			messageText = messageObject.toString() + printArguments(arguments);

		}
		return messageText;
	}

	/**
	 * Creates a Message string and dynamically set the arguments
	 * 
	 * @param messageObject
	 * @param arguments
	 * @return Message string with dynamically set the arguments
	 */
	public static String replaceArguments(Message messageObject) {

		return replaceArguments(messageObject);
	}

}
